<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/2/11 0011
 * Time: 下午 5:35
 */
namespace app\api\controller;

use app\admin\model\Groupdetail;
use app\admin\model\Groupproduct;
use app\common\validate\MakeGroup;
use think\Request;
use app\api\service\Group as GroupService;

class Group extends Base{
    /**
     * 用户开团或参团
     * @return array|\think\response\Json
     * @throws ParameterException
     */
    public function makeGroup(Request $request){
        //参数 1.线上团购列表id,2.团购方式
        //先判断此团用户是否正在参与
        (new MakeGroup())->goCheck();
        $orderdata = $request->param();
        $products = $orderdata['products'];
        $uid = $orderdata['uid'];
        unset($orderdata['products']);
        $makegroup = new GroupService();
        $result = $makegroup->makegroup($uid,$orderdata,$products);
        if(isset($result['pass']) && $result['pass']){
            return show(config('status.SUCCESS_STATUS'), '创建订单成功', $result);
        }else{
            if(!isset($result['ExceptionInfo'])){
                return show(config('status.ERROR_STATUS'), '创建订单失败，库存不足', $result);
            }else{
                return show(config('status.ERROR_STATUS'), $result['ExceptionInfo']['msg'], $result['ExceptionInfo']['msg']);
            }
        }
    }

    /**
     * 线上拼团商品列表
     * @return \think\response\Json
     */
    public function groupList(){
        $nowtime = time();
        $join = [
            ['__PRODUCT__ b','b.id=a.product_id'],
            ['__STOCK__ c','c.product_id=a.product_id']
        ];
        $field = 'a.*,b.name,b.price,b.img_url,b.unit,b.spec,c.marketable';
        $groupList = db('groupproduct')->alias('a')->where('a.status',1)->where('a.start_time','<=',$nowtime)->where('a.end_time','>=',$nowtime)->where('c.marketable','gt',0)->join($join)->field($field)->select();
        if($groupList){
            foreach ($groupList as &$v){
                if($nowtime >= $v['start_time']){
                    $v['is_start'] = 1;
                }else{
                    $v['is_start'] = 0;
                }
            }
            return show(config('status.SUCCESS_STATUS'),'ok',$groupList);
        }else{
            return show(config('status.ERROR_STATUS'),'暂无数据',NULL);
        }
    }

    /**
     * 拼团详情
     * @param Request $request
     * @return \think\response\Json
     */
    public function groupDetails(Request $request){
        $param = $request->param();
        if(!empty($param['id']) && !empty($param['uid'])){
            $join = [
                ['__PRODUCT__ b','b.id=a.product_id'],
                ['__BRAND__ c','c.id=b.brand_id']
            ];
            $field = 'a.*,b.name,b.price,b.img_url,b.unit,b.spec,b.describe,b.address,b.quality_time,b.brand_id,b.packing,b.storage_mode,b.img_urls as banner,b.detections,b.cookbook_ids,c.name as bname';
            $group = db('groupproduct')->alias('a')->join($join)->where(['a.id'=>$param['id']])->field($field)->find();
            if($group){
                $mygroup = Groupdetail::where(['member_id'=>$param['uid'],'group_id'=>$group['id'],'status'=>1,'is_pay'=>1])->find();
                if($mygroup){
                    $group['my_isgroup'] = 1;
                }else{
                    $group['my_isgroup'] = 0;
                }
                $productdetails = db('image')->where('related_id',$group['product_id'])->field('img_url')->select();
                $listarr = [];
                if($productdetails){
                    foreach ($productdetails as $v){
                        array_push($listarr,$v['img_url']);
                    }
                }
                $group['productdetails'] = $listarr;
                $group['detections'] = explode(',',$group['detections']);
                $group['banner'] = explode(',',$group['banner']);
                $group['cookbook_ids'] = explode(',',$group['cookbook_ids']);
                $nowtime = time();
                $where['status'] = 1;
                $where['group_id'] = $group['id'];
                $where['is_pay'] = 1;
                $where['end_date'] = ['gt',$nowtime];
                $groupdetail = Groupdetail::where($where)->select();
                if($groupdetail){
                    $coloneusers = $this->getcolone($groupdetail,$group);
                    $group['groupdetail'] = $coloneusers;
                    $group['alreadygroupnum'] = count($groupdetail);
                }
                return show(config('status.SUCCESS_STATUS'),'ok',$group);
            }else{
                return show(config('status.ERROR_STATUS'),'数据异常','数据异常');
            }
        }else{
            return show(config('status.ERROR_STATUS'),'参数异常','参数异常');
        }


    }

    /**
     * 获取团长信息
     * @param $groupdetail
     * @param $group
     * @return array|false|mixed|\PDOStatement|string|\think\Collection
     */
    private function getcolone($groupdetail,$group){
        $colonelIDs = [];
        $unigroupIds = [];
        foreach ($groupdetail as $value){
            if($value['member_id'] == $value['originator']){
                //开团的用户（团长）
                array_push($colonelIDs,$value['member_id']);
                array_push($unigroupIds,$value['unigroup_id']);
            }
        }
        $Member = \app\admin\model\Member::where('id','in',$colonelIDs)->field('id,avatar,account_number')->select();
        $unigroups = Groupdetail::where('id','in',$unigroupIds)->select();
        foreach ($unigroups as &$v){
            foreach ($Member as $value){
                if($v['member_id'] == $value['id']){
                    $v['member'] = $value;
                    $unis = Groupdetail::where(['unigroup_id'=>$v['unigroup_id'],'is_pay'=>1])->count();
                    $v['surplus_num'] = $group['group_succ_count'] - $unis;  //当前团还剩人数
                }
            }
        }
        return $unigroups;
    }

    /**
     * 我的拼团列表
     * @return \think\response\Json
     */
    public function myGroupList(Request $request){
        $param = $request->param();
        if(\app\admin\model\Member::checkUser($param['uid'])){
            $join = [
                ['__GROUPPRODUCT__ b','b.id=a.group_id'],
                ['__PRODUCT__ c','c.id=b.product_id']
            ];
            $field = 'a.*,b.group_price,b.group_succ_count,c.name,c.img_url,c.unit,c.spec,c.price';
            $Groupdetail = db('groupdetail')->alias('a')->join($join)->where('a.status','in',[1,2,3])->where(['a.member_id'=>$param['uid'],'a.is_pay'=>1])->field($field)->select();
            foreach ($Groupdetail as &$value){
                $groupcount = Groupdetail::where(['unigroup_id'=>$value['unigroup_id'],'is_pay'=>1])->count();
                $value['shengyu'] = $value['group_succ_count'] - $groupcount;
            }
            if($Groupdetail){
                return show(config('status.SUCCESS_STATUS'),'ok',$Groupdetail);
            }else{
                return show(config('status.ERROR_STATUS'),'您没有参加过团购','');
            }
        }else{
            return show(config('status.ERROR_STATUS'),'用户参数异常','用户参数异常');
        }


    }
}